package com.syj.qdp.framework.skywalking.config;

import com.syj.qdp.framework.common.enums.WebFilterOrderEnum;
import com.syj.qdp.framework.skywalking.core.aop.BizTraceAspect;
import com.syj.qdp.framework.skywalking.core.filter.TraceFilter;
import io.opentracing.Tracer;
import io.opentracing.util.GlobalTracer;
import org.apache.skywalking.apm.toolkit.opentracing.SkywalkingTracer;
import org.springframework.boot.autoconfigure.condition.ConditionalOnClass;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.boot.autoconfigure.web.servlet.ConditionalOnMissingFilterBean;
import org.springframework.boot.web.servlet.FilterRegistrationBean;
import org.springframework.context.annotation.Bean;

import javax.servlet.Filter;

/**
 * @author Lyon
 */
@ConditionalOnClass(TracerProperties.class)
@ConditionalOnProperty(prefix = "syj.qdp.tracer", value = "enable")
@ConditionalOnMissingBean
public class TracerAutoConfiguration {

    @Bean
    @ConditionalOnMissingBean
    Tracer tracer() {
        SkywalkingTracer skywalkingTracer = new SkywalkingTracer();
        GlobalTracer.register(skywalkingTracer);
        return skywalkingTracer;
    }

    @Bean
    @ConditionalOnMissingBean
    public BizTraceAspect bizTraceAspect(Tracer tracer) {
        return new BizTraceAspect(tracer);
    }

    @Bean
    @ConditionalOnMissingFilterBean
    public FilterRegistrationBean<? extends Filter> traceFilter() {
        FilterRegistrationBean<TraceFilter> registrationBean = new FilterRegistrationBean<>();
        registrationBean.setFilter(new TraceFilter());
        registrationBean.setOrder(WebFilterOrderEnum.TRACE_FILTER);
        return registrationBean;
    }
}
